package retrofit2.harmony;

import ohos.aafwk.ability.AbilityPackage;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.GsonConverterFactory;
import retrofit2.harmony.net.WanAndroid;

public class MyApplication extends AbilityPackage {
    private static MyApplication sInstance;
    private Retrofit mRetrofit;
    private WanAndroid mWanAndroid;

    @Override
    public void onInitialize() {
        super.onInitialize();
        sInstance = this;
        initRetrofit();
        //创建服务接口
        mWanAndroid = mRetrofit.create(WanAndroid.class);
    }

    /**
     * 初始化Retrofit
     */
    private void initRetrofit() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String log) {
                HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "RetrofitHarmony");
                HiLog.info(label, log);
            }
        });
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        //日志拦截器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();
        //创建Retrofit实例
        mRetrofit = new Retrofit.Builder()
                .callFactory(okHttpClient)
                .baseUrl("https://www.wanandroid.com")
                //RxJava适配器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                //Gson转换器
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static MyApplication getInstance() {
        return sInstance;
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

    public WanAndroid getWanAndroid() {
        return mWanAndroid;
    }
}
